package org.linlinjava.litemall.db.service.oder_manage;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.AgedmallLgRfidGoodsCurStatMapper;
import org.linlinjava.litemall.db.dao.LitemallOrderGoodsMapper;
import org.linlinjava.litemall.db.dao.LitemallOrderItemMapper;
import org.linlinjava.litemall.db.dao.LitemallOrderMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedMallOrderMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.LgBaseInfoStatConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.PageUtils;
import org.linlinjava.litemall.db.util.Query;
import org.linlinjava.litemall.db.vo.order_manage.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author wj
 * @date 2021/5/27 18:55
 */
@Service
@Transactional
public class AgedMallOrderDbService {

    @Resource
    private AgedMallOrderMapper agedMallOrderMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Autowired
    private LitemallOrderItemMapper litemallOrderItemMapper;


    public List<OrderListBackVo> getOrderManageList(String adminPhone,Integer storeId, String phone,Integer orderStatus,LocalDateTime startTime,LocalDateTime endTime,Integer isAfterSale){
       return agedMallOrderMapper.selectOrderManageList(adminPhone,storeId,phone,orderStatus,startTime,endTime,isAfterSale);
    }

    public List<OrderGoodsBackVo> getOrderGoodsByStoreIdAndOrderId(Integer storeId, Integer orderId){
        return agedMallOrderMapper.selectOrderStoreGoodsByStoreIdAndOrderId(storeId,orderId);
    }

    public List<OrderGoodsBackVo> getOrderGoodsByOrderId(Integer orderId){
        return agedMallOrderMapper.selectOrderStoreGoodsByOrderId(orderId);
    }

    /**
     * 获取管理系统的订单列表
     * #待配货 agedmall_logistics_package_info ship_status =1 打包完成
     * #待送货 agedmall_logistics_package_info ship_status =2 配货完成
     * #待取货 agedmall_lease_goods_return_record get_goods_style = 0 and receive_time is null
     * #待维护  agedmall_lease_goods_return_record get_goods_style = 0 and receive_time is not null
     * #待结算 agedmall_agent_settle_detail  proxy_status = 0待结算 1 已结算
     *
     * #手机号 litemall.litemall_order mobile 字段
     * #门店 litemall.litemall_order province 省 city 市 county 县;门店id litemall_order_goods store_id
     * #人员 agedmall_order_logistics delivery_man_id员工id 发货，售后，归还 ；
     * #     agedmall_order_delivery_person delivery_man_id 员工id 配货 送货 维护 用户自取
     * #     agedmall_pickup_goods_record maintain_man_id，delivery_man_id
     * #     agedmall_return_goods_record delivery_man_id 配送员id
     * #门店下只有配送人员
     * #打包的订单号是总订单号
     * #取货费用没有
     * #维护费用没有
     * @param storeOrderAdminQuery
     * @return
     */
    public Object getApageAdminOrder(StoreOrderAdminQuery storeOrderAdminQuery) {
        Page page = PageHelper.startPage(storeOrderAdminQuery.getPageNum(), storeOrderAdminQuery.getPageSize());
        List<AgedAdminOrderItemInfoVo> itemInfoVoList = agedMallOrderMapper.getAdminOrderList(storeOrderAdminQuery);
        Map<String, AgedAdminOrderDataVo> orderDataVoMap = new HashMap<>();
        Map<String, List<AgedAdminOrderItemInfoVo>> orderItemMap = new HashMap<>();
        for(AgedAdminOrderItemInfoVo item:itemInfoVoList) {
            String orderSn = item.getOrderSn();
            List<AgedAdminOrderItemInfoVo> list = orderItemMap.get(orderSn);
            if(list == null) {
                list = new ArrayList<>();
                orderItemMap.put(orderSn, list);
            }
            if(orderDataVoMap.get(orderSn) == null) {
                AgedAdminOrderDataVo dataVo = new AgedAdminOrderDataVo();
                dataVo.setOrderCode(orderSn);
                dataVo.setStoreName(item.getStoreName());
                dataVo.setCreateTime(item.getCreateTime());
                if(item.getOrderStatus() == OrderUtil.STATUS_CANCEL.toString()){
                    dataVo.setOrderStatus(OrderUtil.STATUS_ORDER_CANCEL.toString());
                }
                dataVo.setFreightPrice(item.getFreightPrice());
                dataVo.setPickPrice(item.getPickPrice());
                dataVo.setMaintainPrice(item.getMaintainPrice());
                dataVo.setDeliveryPrice(item.getDeliveryPrice());
                orderDataVoMap.put(orderSn, dataVo);
            }
            list.add(item);
        }
        for(String orderSn:orderItemMap.keySet()) {
            List<AgedAdminOrderItemInfoVo> itemList = orderItemMap.get(orderSn);
            AgedAdminOrderDataVo dataVo = orderDataVoMap.get(orderSn);
            dataVo.initGoods(itemList);
        }

        List<AgedAdminOrderDataVo> orderDataVoList = new ArrayList<>();
        orderDataVoList.addAll(orderDataVoMap.values());
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("data", orderDataVoList);
        return map;
    }

    /**
     * 获取订单号下的rfid列表信息
     * @param params 参数orderId订单号编号
     * @return
     */
    public List<String> getOrderRfidList(Map<String,Object> params) {
        List<String> rfidStrList = agedMallOrderMapper.getOrderEquRfidList(params);
        List<String> resutlList = new ArrayList<>();
        for(String str: rfidStrList) {
            String[] arr = str.split(",");
            resutlList.addAll(Arrays.asList(arr));
        }
        return resutlList;
    }

    /**
     * 更新rfid状态信息
     * @param  orderCode
     * @param  rfids
     * @param  type 类型1-软链 2-医柜
     * @return
     */
    public int updateRfidCurOrderCode(String orderCode, List<String> rfids,Integer type) {
        return agedMallOrderMapper.updateRfidCurOrderCode(orderCode, rfids,type);
    }

    /**
     * 获取用户租赁申请归还的订单号信息
     * @param uid
     * @param rfid
     * @return
     */
    public OrderCodeInfo getUserLeaseApplyBackOrderInfo(long uid, String rfid) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("rfid", rfid);
        OrderCodeInfo orderCodeInfo = agedMallOrderMapper.getUserLeaseApplyBackOrderInfo(params);
        return orderCodeInfo;
    }

    /**
     *
     * @param bigOrderCode
     * @return
     */
    public BigDecimal getOrderFeeByGoodsType(String bigOrderCode, String childOrderCode, String goodsType) {
         LitemallOrderGoodsExample orderGoodsExample = new LitemallOrderGoodsExample();
         orderGoodsExample.createCriteria().andOrderCodeEqualTo(bigOrderCode).andChildOrderCodeEqualTo(childOrderCode)
                 .andTypeEqualTo(goodsType);
         List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
         BigDecimal totalFee = BigDecimal.ZERO;
         orderGoodsList.stream().forEach(o->{
             BigDecimal gPrice = o.getPrice();
             int count = o.getNumber();
             totalFee.add(gPrice == null ? BigDecimal.ZERO : gPrice.multiply(new BigDecimal(count)));
         });
         return totalFee;
    }

    /**
     * 更新子订单结算信息
     * @param childOrderCode
     * @param rent
     * @param refund
     * @param deliverFee
     * @return
     */
    public int updateChildOrderPayRentAndRefund(String childOrderCode, BigDecimal rent, BigDecimal refund, BigDecimal deliverFee) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andChildOrderCodeEqualTo(childOrderCode);
        LitemallOrderItem orderItem = new LitemallOrderItem();
        orderItem.setRefundAmount(refund);
        if(deliverFee != null && deliverFee.compareTo(BigDecimal.ZERO) > 0) {
            orderItem.setFreightPrice(deliverFee);
        }
        orderItem.setPayRent(rent);
        return litemallOrderItemMapper.updateByExampleSelective(orderItem, orderItemExample);
    }


    //更新买断的商品子订单结算信息

    /**
     *
     * @param childOrderCode
     * @param rent
     * @param refund
     * @param deliverFee
     * @return
     */
    public int buyoutUpdateChildOrderPayRentAndRefund(String childOrderCode, BigDecimal rent, BigDecimal refund, BigDecimal deliverFee,BigDecimal buyOutPrice) {
        LitemallOrderItemExample orderItemExample = new LitemallOrderItemExample();
        orderItemExample.createCriteria().andChildOrderCodeEqualTo(childOrderCode);
        LitemallOrderItem orderItem = new LitemallOrderItem();
        //orderItem.setRefundAmount(refund);
        if(deliverFee != null && deliverFee.compareTo(BigDecimal.ZERO) > 0) {
            orderItem.setFreightPrice(deliverFee);
        }
        if (refund!=null&&refund.compareTo(BigDecimal.ZERO)>=0){
            orderItem.setRefundAmount(refund);
            //完成状态
            orderItem.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
            //orderItem.setGoodsType("sale");
            //买断
            orderItem.setIsBuyout(1);
            orderItem.setBuyoutPrice(buyOutPrice);
            orderItem.setUpdateTime(LocalDateTime.now());
        }else{
            //待结算
            orderItem.setOrderStatus(OrderUtil.STATUS_RETURN_SETTLE);
            //orderItem.setGoodsType("sale");
            //买断
            orderItem.setIsBuyout(1);
            orderItem.setBuyoutPrice(buyOutPrice);
            orderItem.setUpdateTime(LocalDateTime.now());
        }
        orderItem.setPayRent(rent);
        return litemallOrderItemMapper.updateByExampleSelective(orderItem, orderItemExample);
    }
}
